#include "StdAfx.h"
#include "MatchOreFactory.h"

#include "hdimineview.h"


CMatchOreFactory::CMatchOreFactory(dmDbDatabase* pPeriodLoopDB, HDiMineView* pHView)
	: m_pView(pHView)
	, m_pLoader(NULL)
	, m_pConstraintParam(NULL)
	, m_pOptimizer(NULL)
	, m_pResultManager(NULL)
{
	m_pLoader = new CRegionBlastPileLoader;
	m_pConstraintParam = new CConstraintParam;
	m_pOptimizer = new CBlastPileOptimizer;
	m_pResultManager = new COptimumResultManager(m_pView, pPeriodLoopDB);
}

CMatchOreFactory::~CMatchOreFactory(void)
{
	if (m_pLoader != NULL)
	{
		delete m_pLoader;
		m_pLoader = NULL;
	}

	if (m_pConstraintParam != NULL)
	{
		delete m_pConstraintParam;
		m_pConstraintParam = NULL;
	}

	if (m_pOptimizer != NULL)
	{
		delete m_pOptimizer;
		m_pOptimizer = NULL;
	}

	if (m_pResultManager != NULL)
	{
		delete m_pResultManager;
		m_pResultManager = NULL;
	}
}

bool CMatchOreFactory::InitDisplay()
{
	if (NULL == m_pLoader || NULL == m_pResultManager)
		return false;

	for (int i=0; i<m_pLoader->GetCount(); ++i)
	{
		m_pResultManager->SetBlastPile(m_pLoader->GetAt(i));
		m_pResultManager->InitDisplayRegionDB();
	}

	return true;
}

static void get_optimized_elem(std::set<std::string>& sStrOptimizedElem, CConstraintParam* pConstraintParam)
{
	if (NULL == pConstraintParam)
		return;

	sStrOptimizedElem.clear();

	GRADE_CONSTRAINT_PARAM* pGradeConstraintParam = NULL;
	int iGradeConstraintParamNum = 0;
	pConstraintParam->GetGradeConstraintParam(pGradeConstraintParam, iGradeConstraintParamNum);
	for (int i=0; i<iGradeConstraintParamNum; ++i)
	{
		std::string strElem = pGradeConstraintParam[i].grade_name;
		sStrOptimizedElem.insert(strElem);
	}
}

bool CMatchOreFactory::UpdateDisplay(double dTruckTon)
{
	if (NULL == m_pLoader || NULL == m_pResultManager || NULL == m_pConstraintParam)
		return false;

	std::set<std::string> sStrOptimizedElem;
	get_optimized_elem(sStrOptimizedElem, m_pConstraintParam);

	for (int i=0; i<m_pLoader->GetCount(); ++i)
	{
		m_pResultManager->SetBlastPile(m_pLoader->GetAt(i));
		m_pResultManager->SetOptimizedElem(sStrOptimizedElem);
		m_pResultManager->SetMinePeriodDisplay();
	}

	CString strFile = m_pConstraintParam->GetRepFile();
	char* pFile = strFile.GetBuffer(strFile.GetLength());
	m_pResultManager->SaveRepTable(pFile,dTruckTon);

	return true;
}

